﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using UCenter.PluginFramework;
using UCenter.ContactService;

namespace UCenter.ContactFromLiveID
{
    [Extension]
    public class LiveIDContactService : PlugInContextBase
    {
        public override void Initialize()
        {
            // Init consent url
            WindowsLiveLogin wll = new WindowsLiveLogin(true);
            wll.ReturnUrl = HttpContext.Current.Request.Url.ToString();
            string consentUrl = wll.GetConsentUrl("Contacts.View");
            this.ExtendedData["ConsentUrl"] = consentUrl;

            string cookieName = this.Current.Settings["DelAuthCookie"].Value;

            DateTime ExpireCookie = DateTime.Now.AddYears(-10);
            DateTime PersistCookie = DateTime.Now.AddYears(10);
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];

            WindowsLiveLogin.ConsentToken Token = null;
            if (authCookie != null)
            {
                Token = wll.ProcessConsentToken(authCookie.Value);

                if ((Token != null) && !Token.IsValid())
                {
                    Token = null;
                }
            }

            authCookie = new HttpCookie(cookieName);
            string action = HttpContext.Current.Request["action"];
            if (action == "delauth")
            {
                Token = wll.ProcessConsent(HttpContext.Current.Request.Form);
                if (Token != null)
                {
                    authCookie.Value = Token.Token;
                    authCookie.Expires = PersistCookie;
                }
                else
                {
                    authCookie.Expires = ExpireCookie;
                }

                HttpContext.Current.Response.Cookies.Add(authCookie);
            }
            this.ExtendedData["Token"] = Token;
        }

        public override ResultDataDictionary Execute(params object[] obj)
        {
            UContractCollection list = new UContractCollection();
            LiveContractCollection col = LiveIDHelper.GetLiveContracts();

            foreach (var c in col)
            {
                UContract uc = new UContract();
                uc.Email = c.Emails.Address;
                uc.Name = c.Profiles.DisplayName;
                list.Add(uc);
            }

            ResultDataDictionary resultData = new ResultDataDictionary();
            resultData.Add("Emails", list);

            return resultData;
        }

        public override void Dispose()
        {
            
        }
    }
}
